#!/usr/bin/python2
#-*-python-*-

import getopt
import cf
import sys
import os
import re

# --------------------------------------------------------------------
# Parse command line options
# --------------------------------------------------------------------
iam   = os.path.basename(sys.argv[0])
usage = "USAGE: %s [-a opts] [-d dir] [-f format] [-o outfile] [-r opts] [-t table] [-u VN] [-v] [-V] FILE [FILE ...]" % iam

try:
    opts, infiles = getopt.getopt(sys.argv[1:], "a:d:f:o:r:t:u:vV", 
                                  ['aggregate_options=',
                                   'directory=',
                                   'format=',
                                   'netcdf4',
                                   'output=',
                                   'read_options=',
                                   'table=',
                                   'umversion=',
                                   'verbose',
                                   'Version',
                                   ])
except getopt.GetoptError, err:
    # print help information and exit:
    print iam, str(err)    
    print usage
    sys.exit(2)
#--- End: try

# Defaults
format_out        = 'NETCDF3_CLASSIC'
directory         = None
outfile           = None
verbose           = False
aggregate_options = {}
read_options      = {'close'         : True,
                     'ignore_ioerror': False,
                     }

for option, arg in opts:
    if option in ('-d', '--directory'):
        directory = arg
        # Try to create non-existent directories
        try:
            os.makedirs(directory)
        except os.error:
            pass
    elif option in ('-f', '--format'):
        format_out = arg
    elif option in ('-o', '--output'):
        outfile = arg
    elif option in ('-t', '--table'):
        cf.pp._stash2standard_name = cf.pp.read_stash2standard_name(table=arg)
    elif option in ('-u', '--umversion'):
        cf.pp._UMVERSION = arg.replace('.', '0', 1)
    elif option in ('-v', '--verbose'):
        verbose = 1
    elif option in ('-a', '--aggregate_options'):
        for opt in arg.split(','):
            key, value = opt.split('=')
            if value == '0':
                value = False
            else:
                value = True
            aggregate_options[key] = value                         
    elif option in ('-r', '--read_options'):
        for opt in arg.split(','):
            key, value = opt.split('=')
            if value == '0':
                value = False
            else:
                value = True
            read_options[key] = value                         
    elif option in ('-V', '--Version'):
        print iam, 'using cf-python version', cf.__version__
        sys.exit(0)
    else:
        print usage
        assert False, "Unhandled option:"+option
#--- End: for

if not infiles:
    print iam,"ERROR: Must provide at least one input PP file."
    print usage
    sys.exit(2)
#--- End: if

if read_options.has_key('aggregate') and not read_options['aggregate']:
    pass
else:
    read_options['aggregate'] = aggregate_options

if outfile is not None and directory is not None:
    print iam,"ERROR: Can't set an output directory and an output file"
    print usage
    sys.exit(1) 
#--- End: if

# --------------------------------------------------------------------
# Read the PP files, aggregate the fields and write them out as netCDF
# files
# --------------------------------------------------------------------
if outfile:
    # One output netCDF file for all input PP files
    try:        
        f = cf.read(infiles, **read_options)
    except Exception as error:
        print iam, 'ERROR reading file:', error
        sys.exit(1)    
    #--- End: try

    file = outfile
    if verbose:
        ninfiles = len(infiles)
        ncf      = len(f)
        print "%d input PP file%s contain%s %d CF field%s:" % \
            (ninfiles,
             ('' if ninfiles==1 else 's' ),
             ('' if ncf==1      else 's'),
             ncf,
             ('s' if ncf>1 else '' ))
        print repr(f)
    #--- End: if

    # Write the netCDF file, deleting each field after it has been
    # written
    if f:
        try:        
            cf.write(f, file, format=format_out)
        except Exception as error:
            print iam, 'ERROR writing file:', error
            sys.exit(1)

else:
    # One output netCDF file per input PP file 
    for infile in infiles:
        try:        
            f = cf.read(infile, **read_options)
        except Exception as error:
            print iam, 'ERROR reading file:', error
            sys.exit(1)
        #--- End: try

        file = '%s.nc' % re.sub('\.pp$', '', infile)
        if directory is not None:
            head, tail = os.path.split(file)
            head       = directory
            file       = os.path.join(head, tail)
        if verbose:
            ncf = len(f)
            print "1 input PP file contains %d CF field%s:" % \
                (ncf,
                 ('' if ncf==1 else 's' ))
            print repr(f)
        #--- End: if

        # Write the netCDF file, deleting each field after it has been
        # written
        if f:
            cf.write(f, file, format=format_out)
    #--- End: for
#--- End: if
